/**
 * Created by weid on 2016/9/21.
 */
import angular from 'angular';
import util from '@yunke/core/util';
import ui from '@yunke/core/ui';
import 'angular-ui';
import '../css/org_management.css';
import '@yunke/jqtree';
import '@yunke/angular-ui/lib/yunkeTreeSelect';

const app = angular.module('organization', ['ngPublicUI', 'angular.directive.yunkeTreeSelect']);

app.controller('ctrlOrganization', ['$scope', 'sveOrg', ($scope, sveOrg) => {

    // 分页
    $scope.pageIndex = 1;
    $scope.pageSize = 10;
    $scope.pageChange = ($pageIndex, $pageSize) => {
        $scope.pageIndex = $pageIndex;
        $scope.pageSize = $pageSize;
        sveOrg.renderUserList($scope);
    };

    // 渲染数据列表
    sveOrg.renderOrgList($scope);

    // 搜索
    $scope.search = () => {
        $scope.pageIndex = 1;
        sveOrg.renderUserList($scope);
    };

    // 设置兼职公司 或 用户角色关联
    $scope.setRelateTemplateUrl = require('./dialog/set_relate.html');
    $scope.setRelate = ($dialog, $dialogScope, item = {}) => {
        sveOrg.getRelateInfo(item.UserGUID).success(res => {
            $dialogScope.userInfo = res.data.userInfo;
        });

        $dialogScope.selectable = (node) => {
            return !(node.children && node.children.length);
        };

        // 用户角色
        sveOrg.getRoleList().success(res => {
            sveOrg.recursion(res.data);
            $dialogScope.userRoleList = res.data;
            item.roleList.forEach(v => {
                v.id = v.role_id;
                v.name = v.role_name;
            });
            $dialogScope.curUserRole = item.roleList;
        });

        // 兼职公司
        sveOrg.getOrgList().success(res => {
            sveOrg.recursion(res.data.orgList);
            $dialogScope.companyList = res.data.orgList;
            item.partTimeBUList.forEach(v => {
                v.id = v.bu_guid;
                v.name = v.BUName;
            });
            $dialogScope.curCompany = item.partTimeBUList;
        });
    };
    $scope.saveRelate = ($dialog, $dialogScope, item = {}) => {
        const relateInfo = {
            userGUID: item.UserGUID,
            roleList: [],
            partTimeBUGUIDList: []
        };
        $dialogScope.curUserRole.forEach(v => {
            relateInfo.roleList.push(v.id);
        });
        $dialogScope.curCompany.forEach(v => {
            relateInfo.partTimeBUGUIDList.push(v.id);
        });
        sveOrg.saveRelateInfo(relateInfo).success(() => {
            ui.showTip('保存成功');
            sveOrg.renderUserList($scope);
        });
    };

    // 设定为区域负责人 或 取消区域负责人身份
    $scope.setPrincipal = (item = {}) => {
        let text = item.isAreaCharge === 0 ?
            `<div class="text-center">确定要将“${item.UserName}”设定为区域负责人吗？<br>区域负责人能看到所属区域下的全部数据。</div>` :
            `<div class="text-center">确定要取消“${item.UserName}”的区域负责人身份吗？<br>一旦取消，该用户将不能看到所属区域下的全部数据，只能看到自己的数据。</div>`;
        util.confirm(text, {
            ok() {
                sveOrg.setPrincipal(item.UserGUID).success(() => {
                    sveOrg.renderUserList($scope);
                });
            }
        });
    };
}]);

app.service('sveOrg', ['$http', ($http)=> {
    return {
        getRoleList(keyword = ''){
            return $http.get(
                G_CONFIG['api_prefix'] + 'user-auth/role-list',
                {
                    params: {
                        keyword
                    }
                }
            )
        },
        getOrgList(){
            return $http.get(G_CONFIG['api_prefix'] + 'user-auth/get-org-list');
        },
        recursion(data, otherFn){
            data.forEach(v => {
                v.name = v.name || v.BUName || v.role_name;
                v.id = v.BUGUID || v.role_id || v.field;
                if (v.son instanceof Array && v.son.length) {
                    v.children = v.son;
                    this.recursion(v.son);
                } else if (v.children instanceof Array && v.children.length) {
                    this.recursion(v.children);
                }
                otherFn && otherFn(v);
            });
        },
        renderOrgList($scope){
            this.getOrgList().success(res => {

                // 递归改变数据结构字段，设置 $scope.curOrgId
                this.recursion(res.data.orgList, (item) => {
                    if (!$scope.curOrgId && item.BUGUID) {
                        $scope.curOrgId = item.BUGUID;
                    }
                });

                this.renderTreeMenu(res.data.orgList, $scope);
                this.renderUserList($scope);
            });
        },
        renderTreeMenu(data, $scope){
            $('#org-tree').tree({
                autoOpen: 1,
                data: data
            }).on('tree.select', (event) => {
                $scope.curOrgId = event.node.BUGUID;
                $scope.pageIndex = 1;
                this.renderUserList($scope);
            });
        },
        getUserList($scope){
            return $http.get(
                G_CONFIG['api_prefix'] + 'user-auth/user-list',
                {
                    params: {
                        buGUID: $scope.keyword ? '' : $scope.curOrgId,
                        keyword: $scope.keyword || '',
                        pageIndex: $scope.pageIndex,
                        pageSize: $scope.pageSize
                    }
                }
            )
        },
        renderUserList($scope){
            this.getUserList($scope).success(res => {
                $scope.pageTotal = res.data.pageTotal;
                $scope.userList = res.data.userList;
            });
        },
        getRelateInfo(userGUID){
            return $http.get(
                G_CONFIG['api_prefix'] + 'user-auth/get-user-info',
                {
                    params: {
                        userGUID
                    }
                }
            )
        },
        saveRelateInfo(params){
            return $http.post(
                G_CONFIG['api_prefix'] + 'user-auth/set-user-role-and-business',
                params
            )
        },
        setPrincipal(userGUID){
            return $http.get(
                G_CONFIG['api_prefix'] + 'user-auth/set-area-charge',
                {
                    params: {
                        userGUID
                    }
                }
            )
        }
    };
}]);
